package org.systemsbiology.addama.sequencing.util;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import junit.framework.*;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: jlin
 * Date: 8/19/11
 * Time: 10:04 AM
 * To change this template use File | Settings | File Templates.
 */
public class SolrHttpGetPostTest extends TestCase {

    public void testGet(String url) {
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));
            int statusCode = client.executeMethod(get);
            System.out.println("Get" + url + "\nStatus code:" + statusCode);
           // System.out.println(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
            JSONObject resp = new JSONObject(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
            //return resp;
            System.out.println(resp);
            //{"response":{"start":0,"docs":[{"limsadminYoMaxNum":512,"limsKey":"dudley_limsadminkey","limsadminYadBoxNum":6,"limsadminLOligoCount":240,"limsadminYpgPosition":"A1","limsadminYoBoxNum":7,"limsadminYseqCount":73,"limsadminYseqRADCount":52,"limsadminYadMaxNum":424,"limsadminYseqOligoCount":13,"limsadminKey":"dudley_limsadminkey","limsadminYpgMaxNum":1768,"limsadminChemCount":367,"limsadminYcgsCount":6,"limsadminDOligoMaxNum":532,"limsadminPlasmidBoxNum":4,"limsadminYoPosition":"G3","limsadminChemMaxNum":367,"limsadminDOligoCount":532,"limsadminYadCount":424,"limsadminYadPosition":"B9","limsadminCrossingCount":12,"limsadminLOligoMaxNum":240,"limsadminYpgCount":1768,"limsadminYoCount":791,"limsadminPlasmidMaxNum":323,"limsadminPlasmidCount":323,"allFields":["dudley_limsadminkey","791","512","7","G3","424","424","6","B9","1768","1768","20","A1","367","367","532","532","240","240","323","323","4","12","73","13","52","6"],"limsadminYpgBoxNum":20}],"numFound":1},"responseHeader":{"status":0,"QTime":2,"params":{"q":"limsadminKey:dudley_limsadminkey","wt":"json"}}}
            JSONObject jsonObject = resp.getJSONObject("response");
            JSONArray jsonArray = jsonObject.getJSONArray("docs");
            JSONObject adminObj = (JSONObject)jsonArray.get(0);
            System.out.println("AdminObj:" + adminObj);
            get.releaseConnection();
            assertEquals(0,0);
        } catch (IOException e) {
            assertEquals(0,1);
            e.printStackTrace();
        } catch (JSONException ej) {
            ej.printStackTrace();
            assertEquals(0,1);
        }
    }

    public JSONObject testGetSolr(String url) {
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));
            int statusCode = client.executeMethod(get);
            System.out.println("Get" + url + "\nStatus code:" + statusCode);
           // System.out.println(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
            JSONObject resp = new JSONObject(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
            //return resp;
            System.out.println(resp);
            //{"response":{"start":0,"docs":[{"limsadminYoMaxNum":512,"limsKey":"dudley_limsadminkey","limsadminYadBoxNum":6,"limsadminLOligoCount":240,"limsadminYpgPosition":"A1","limsadminYoBoxNum":7,"limsadminYseqCount":73,"limsadminYseqRADCount":52,"limsadminYadMaxNum":424,"limsadminYseqOligoCount":13,"limsadminKey":"dudley_limsadminkey","limsadminYpgMaxNum":1768,"limsadminChemCount":367,"limsadminYcgsCount":6,"limsadminDOligoMaxNum":532,"limsadminPlasmidBoxNum":4,"limsadminYoPosition":"G3","limsadminChemMaxNum":367,"limsadminDOligoCount":532,"limsadminYadCount":424,"limsadminYadPosition":"B9","limsadminCrossingCount":12,"limsadminLOligoMaxNum":240,"limsadminYpgCount":1768,"limsadminYoCount":791,"limsadminPlasmidMaxNum":323,"limsadminPlasmidCount":323,"allFields":["dudley_limsadminkey","791","512","7","G3","424","424","6","B9","1768","1768","20","A1","367","367","532","532","240","240","323","323","4","12","73","13","52","6"],"limsadminYpgBoxNum":20}],"numFound":1},"responseHeader":{"status":0,"QTime":2,"params":{"q":"limsadminKey:dudley_limsadminkey","wt":"json"}}}
            JSONObject jsonObject = resp.getJSONObject("response");
            get.releaseConnection();
            assertEquals(0,0);
            return jsonObject;
        } catch (IOException e) {
            assertEquals(0,1);
            e.printStackTrace();
            return null;
        } catch (JSONException ej) {
            ej.printStackTrace();
            assertEquals(0,1);
            return null;
        }
    }

    public void testPost(String url, JSONObject jsonObject) {
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));
            JSONObject postObject = new JSONObject();
            postObject.put("doc", jsonObject);
            JSONObject addObject = new JSONObject();
            addObject.put("add", postObject);
            //"docs":[{"limsadminKey":"dudley_limsadminkey","limsKey":"dudley_limsadminkey","limsadminYoCount":791,
            // "limsadminYoMaxNum":512,"limsadminYoBoxNum":7,"limsadminYoPosition":"G3",
            // "allFields":["dudley_limsadminkey","791","512","7","G3","420","420","6","B5","1768","1768","20","A1","367","367","531","531","240","240","344","344"]}]}}
            post.setParameter("jsonData", "application/json");
            post.setRequestEntity(new StringRequestEntity(addObject.toString(), "application/json", null));
            post.setRequestHeader("Content-Type", "application/json");
            int statusCode = client.executeMethod(post);
            System.out.println("Post " + url + "\nStatus code:" + statusCode);
            System.out.println(IOUtils.toString(post.getResponseBodyAsStream(), "UTF-8"));
            post.releaseConnection();
            assertEquals(0,0);
        } catch (IOException e) {
            e.printStackTrace();
            assertEquals(0,1);

        } catch (JSONException ej) {
            ej.printStackTrace();
            assertEquals(0,1);
        }
    }


    public static void main(String[] args) {
        try {
            String csvFilePath = "/local/lims/sequence_submit/seqX.csv";
            String curledFilePath = "/local/lims/sequence_submit/seqXCurled.txt";
            FileWriter csvFile = new FileWriter(csvFilePath);
            FileWriter curledFile = new FileWriter(curledFilePath);
            PrintWriter outcsv = new PrintWriter(csvFile);
            PrintWriter outcurled = new PrintWriter(curledFile);
            outcsv.println("chemKey,chemName,chemAlias");
            outcsv.println("\"chemTest101\",\"chemName\",\"chemAlias\"");
            outcsv.close();
            csvFile.close();
            String curlCmd = "curl 'http://ravioli.systemsbiology.net:8080/solr/update/csv?commit=true' --data-binary @" + csvFilePath
                    + " -H 'Content-type:text/plain; charset=utf-8'";
            System.out.println(curlCmd);

            /*
            String nospace = "YOABC";
            String[] nospacetk = nospace.split(" ");
            System.out.println("length:" + nospacetk[0]);
            */
            Process p = Runtime.getRuntime().exec(curlCmd);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                outcurled.println(line);
                line = reader.readLine();
            }
            outcurled.close();
            curledFile.close();
            SolrHttpGetPostTest test = new SolrHttpGetPostTest();
            System.out.println("Begin test solr GET");
            JSONObject resp = test.testGetSolr("http://ravioli:8080/solr/select/?q=limsadminKey:dudley_limsadminkey&wt=json&fl=limsadminKey,limsadminYoCount,limsadminYoMaxNum,limsadminYoBoxNum,limsadminYoPosition,limsadminYadCount,limsadminYadMaxNum,limsadminYadBoxNum,limsadminYadPosition,limsadminYpgCount,limsadminYpgMaxNum,limsadminYpgBoxNum,limsadminYpgPosition,limsadminChemCount,limsadminChemMaxNum,limsadminDOligoCount,limsadminDOligoMaxNum,limsadminLOligoCount,limsadminLOligoMaxNum,limsadminPlasmidCount,limsadminPlasmidMaxNum,limsadminPlasmidBoxNum,limsadminCrossingCount,limsadminYseqCount,limsadminYseqOligoCount,limsadminYseqRADCount,limsadminYcgsCount");
//{"response":{"start":0,"docs":[{"limsadminYoMaxNum":512,"limsKey":"dudley_limsadminkey","limsadminYadBoxNum":6,"limsadminLOligoCount":240,"limsadminYpgPosition":"A1","limsadminYoBoxNum":7,"limsadminYseqCount":73,"limsadminYseqRADCount":52,"limsadminYadMaxNum":424,"limsadminYseqOligoCount":13,"limsadminKey":"dudley_limsadminkey","limsadminYpgMaxNum":1768,"limsadminChemCount":367,"limsadminYcgsCount":6,"limsadminDOligoMaxNum":532,"limsadminPlasmidBoxNum":4,"limsadminYoPosition":"G3","limsadminChemMaxNum":367,"limsadminDOligoCount":532,"limsadminYadCount":424,"limsadminYadPosition":"B9","limsadminCrossingCount":12,"limsadminLOligoMaxNum":240,"limsadminYpgCount":1768,"limsadminYoCount":791,"limsadminPlasmidMaxNum":323,"limsadminPlasmidCount":323,"allFields":["dudley_limsadminkey","791","512","7","G3","424","424","6","B9","1768","1768","20","A1","367","367","532","532","240","240","323","323","4","12","73","13","52","6"],"limsadminYpgBoxNum":20}],"numFound":1},"responseHeader":{"status":0,"QTime":2,"params":{"q":"limsadminKey:dudley_limsadminkey","wt":"json"}}}
            //JSONObject respObject = resp.getJSONObject("response");
            JSONArray jsonArray = resp.getJSONArray("docs");
            JSONObject adminObj = (JSONObject)jsonArray.get(0);
            System.out.println("AdminObj:" + adminObj);

            System.out.println("Begin test post");
            /*JSONObject jsonObject = new JSONObject();
            jsonObject.put("limsadminKey", "testadminkey");
            jsonObject.put("limsadminYoMaxNum", "1100");
            jsonObject.put("limsadminYadMaxNum", "1900");
            */
            adminObj.put("limsadminYadMaxNum", "1900");
            test.testPost("http://ravioli:8080/solr/update/json?commit=true", adminObj);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        } catch (Exception ej) {
            ej.printStackTrace();
        }
    }
}
